<template>
  <div class="home">
    <!-- 页面头部 -->
    <el-header class="header">
      <div class="header-content">

        <h1>🏠 社区管理后台 - 首页</h1>
        <div class="header-date">{{ currentDate }}</div>
      </div>
    </el-header>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="4" v-for="(card, index) in statsCards" :key="index">
        <el-card
            class="stat-card"
            :class="`card-${index + 1}`"
            shadow="hover"
        >
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="24" :color="getStatColor(index)">
                <component :is="getStatIcon(index)" />
              </el-icon>
            </div>
            <div class="stat-value">{{ formatStatValue(card.value) }}</div>
            <div class="stat-label">{{ card.label }}</div>
            <div class="stat-trend" v-if="index === 3 || index === 4">
              <el-icon :size="12" color="#67c23a">
                <TrendCharts />
              </el-icon>
              <span>实时更新</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 柱状图：各社区房屋数量 -->
      <el-col :span="12">
        <el-card class="chart-card" title="各社区房屋数量对比">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><Grid /></el-icon>
              <span>各社区房屋数量对比</span>
              <el-tag type="success" size="small">实时数据</el-tag>
            </div>
          </template>
          <div ref="barChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
      <!-- 饼图：房屋状态分布 -->
      <el-col :span="12">
      <el-card class="chart-card" title="房屋状态分布">
        <template #header>
          <div class="card-header">
            <el-icon class="card-icon"><Picture /></el-icon>
            <span>房屋状态分布</span>
            <el-tag type="info" size="small">统计分析</el-tag>
          </div>
        </template>
        <div ref="pieChart1" style="width: 100%; height: 300px;"></div>
      </el-card>
    </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <!-- 折线图：每月收入趋势 -->
      <el-col :span="12">
        <el-card class="chart-card" title="每月账单收入趋势">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><TrendCharts /></el-icon>
              <span>月度收入趋势</span>
              <el-tag type="warning" size="small">趋势分析</el-tag>
            </div>
          </template>
          <div ref="lineChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
      <!-- 环形图：缴费状态分布 -->
      <el-col :span="12">
        <el-card class="chart-card" title="缴费状态分布">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><CircleCheck /></el-icon>
              <span>缴费状态分布</span>
              <el-tag type="danger" size="small">重要指标</el-tag>
            </div>
          </template>
          <div ref="doughnutChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 📰 最新动态（模拟数据） -->
<!--    <el-row class="news-section">
      <el-col :span="24">
        <el-card class="news-card" title="📢 最新动态">
          <template #header>
            <div class="news-header">
              <el-icon class="news-icon"><Bell /></el-icon>
              <span>最新动态</span>
              <el-button type="primary" link>查看更多</el-button>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
                v-for="(item, index) in latestNews"
                :key="index"
                :timestamp="item.time"
                :type="getTimelineType(index)"
                size="large"
            >
              <el-card class="news-item" shadow="hover">
                <div class="news-title">{{ item.title }}</div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>-->
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import * as echarts from 'echarts'

import {
  getCountCommunity, getCountHouse, getCountOwner,
  getCountBill, getCountReport, getCountTodayReport,
  getHouseGroupByCommunity, getHouseGroupByStatus,
  getBillGroupByStatus, getReportCount,
} from '@/api/system/index.js'
import {
  House,
  Grid,
  Picture,
  TrendCharts,
  CircleCheck,
  Bell,
  User,
  HomeFilled,
  Document,
  Money,
  Warning
} from '@element-plus/icons-vue'

// 当前日期
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

onMounted(() => {
  init()
})

const card = reactive({
  communityCount: 0,
  houseCount: 0,
  ownerCount: 0,
  billCount: 0,
  reportCount: 0,
  todayComplaintCount: 0
})

const init = async () => {
  try {
    let resp = await getCountCommunity()
    card.communityCount = resp.data

    resp = await getCountHouse()
    card.houseCount = resp.data

    resp = await getCountOwner()
    card.ownerCount = resp.data

    resp = await getCountBill()
    card.billCount = resp.data

    resp = await getCountTodayReport()
    card.todayComplaintCount = resp.data

    resp = await getReportCount()
    card.reportCount = resp.data
    // 初始化所有图表
    statsCards.value = [
      { label: '总社区数', value: String(card.communityCount) }, // 转字符串显示
      { label: '总房屋数', value: card.houseCount }, // 暂时静态，后续可用 card.houseCount
      { label: '总业主数', value: card.ownerCount },
      { label: '待缴账单', value: card.billCount },
      { label: '待处理工单', value: card.reportCount },
      { label: '今日投诉', value: card.todayComplaintCount },
    ]
    await initBarChart()
    await initPieChart1()
    initLineChart()
    initDoughnutChart()
  } catch (error) {
    console.error('数据加载失败:', error)
  }
}



// 📊 数据概览卡片
const statsCards = ref([])

// 📈 图表 refs
const barChart = ref(null)
const pieChart1 = ref(null)
const lineChart = ref(null)
const doughnutChart = ref(null)

// 📰 最新动态（模拟数据）
const latestNews = ref([
  { time: '2025-10-31 10:00', title: '【公告】小区停水通知', type: 'warning' },
  { time: '2025-10-31 09:30', title: '【新闻】社区文化节圆满结束', type: 'success' },
  { time: '2025-10-31 09:00', title: '【活动】亲子趣味运动会报名开启', type: 'primary' },
  { time: '2025-10-30 18:00', title: '【公告】楼道安全检查通知', type: 'danger' },
])

// 获取统计图标
const getStatIcon = (index) => {
  const icons = ['User', 'HomeFilled', 'Document', 'Money', 'Warning', 'Bell']
  return icons[index] || 'User'
}


// 获取统计颜色
const getStatColor = (index) => {
  const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399', '#ff9f43']
  return colors[index] || '#409eff'
}

// 格式化统计数值
const formatStatValue = (value) => {
  return typeof value === 'number' ? value.toLocaleString() : value
}

// 获取时间轴类型
const getTimelineType = (index) => {
  const types = ['warning', 'success', 'primary', 'danger']
  return types[index] || 'warning'
}

// 1. 各社区房屋数量（柱状图）
const houseGroupByCommunity = ref([])
const initBarChart = async () => {
  try {
    let resp = await getHouseGroupByCommunity()
    houseGroupByCommunity.value = resp.data

    const communityNames = houseGroupByCommunity.value.map(item => item.name)
    const houseCounts = houseGroupByCommunity.value.map(item => item.count)

    const chart = echarts.init(barChart.value)
    const option = {
      title: {
        text: '各社区房屋数量',
        textStyle: { color: '#2c3e50', fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: { color: '#fff' }
      },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: {
        type: 'category',
        data: communityNames,
        axisLine: { lineStyle: { color: '#ddd' } },
        axisLabel: { color: '#666' }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#ddd' } },
        axisLabel: { color: '#666' },
        splitLine: { lineStyle: { color: '#f0f0f0' } }
      },
      series: [{
        type: 'bar',
        data: houseCounts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#4facfe' },
            { offset: 1, color: '#00f2fe' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#3d8bfd' },
              { offset: 1, color: '#0099ff' }
            ])
          }
        }
      }]
    }
    chart.setOption(option)
  } catch (error) {
    console.error('柱状图初始化失败:', error)
  }
}

// 2. 房屋状态分布（饼图）
const houseGroupByStatus = ref([])
const initPieChart1 = async () => {
  try {
    let resp = await getHouseGroupByStatus()
    houseGroupByStatus.value = resp.data

    const chart = echarts.init(pieChart1.value)
    const option = {
      title: {
        text: '房屋状态分布',
        left: 'center',
        top: '0.5%',
        textStyle: { color: '#2c3e50', fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: { color: '#fff' }
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle',
        textStyle: { color: '#666' }
      },
      series: [{
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '55%'],
        data: houseGroupByStatus.value.map(item => ({
          name: item.status,
          value: item.count
        })),
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}\n{c}套\n({d}%)',
          fontSize: 12,
          color: '#333'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }]
    }
    chart.setOption(option)
  } catch (error) {
    console.error('饼图初始化失败:', error)
  }
}

// 3. 每月收入趋势（折线图）
const initLineChart = () => {
  const chart = echarts.init(lineChart.value)
  const option = {
    title: {
      text: '月度收入趋势',
      textStyle: { color: '#2c3e50', fontSize: 16, fontWeight: 'bold' }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      textStyle: { color: '#fff' }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月'],
      axisLine: { lineStyle: { color: '#ddd' } },
      axisLabel: { color: '#666' }
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#ddd' } },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } }
    },
    series: [{
      type: 'line',
      data: [1200, 2000, 1500, 800, 1700, 2200],
      smooth: true,
      itemStyle: {
        color: '#ff6b6b',
        borderColor: '#fff',
        borderWidth: 3
      },
      lineStyle: {
        color: '#ff6b6b',
        width: 3
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
          { offset: 1, color: 'rgba(255, 107, 107, 0.1)' }
        ])
      }
    }]
  }
  chart.setOption(option)
}

// 4. 缴费状态分布（环形图）
const transformStatusData = (rawData) => {
  return rawData.map(item => {
    let name = ''
    switch (item.status) {
      case 1: name = '未支付'; break
      case 0: name = '已支付'; break
    }
    return { value: item.count, name: name }
  })
}

const billGroupByStatus = ref([])
const initDoughnutChart = async () => {
  try {
    let resp = await getBillGroupByStatus()
    billGroupByStatus.value = resp.data

    const chartData = transformStatusData(billGroupByStatus.value)

    const chartDom = doughnutChart.value
    if (!chartDom) return

    const chart = echarts.init(chartDom)
    const option = {
      title: {
        text: '缴费状态分布',
        left: 'center',
        top: '5%',
        textStyle: { color: '#2c3e50', fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: { color: '#fff' },
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle',
        textStyle: { color: '#666' }
      },
      series: [{
        name: '缴费状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '55%'],
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        label: {
          show: true,
          formatter: '{b}\n{c}笔',
          fontSize: 12,
          color: '#333'
        },
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        }
      }]
    }
    chart.setOption(option)
  } catch (error) {
    console.error('环形图初始化失败:', error)
  }
}
</script>

<style scoped>



.home {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.header {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.3);
  border: none;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
}

.header-icon {
  color: #fff;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
}

.header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.header-date {
  font-size: 14px;
  opacity: 0.9;
  font-weight: 400;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  border-radius: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--card-color);
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-1 { --card-color: #409eff; }
.card-2 { --card-color: #67c23a; }
.card-3 { --card-color: #e6a23c; }
.card-4 { --card-color: #f56c6c; }
.card-5 { --card-color: #909399; }
.card-6 { --card-color: #ff9f43; }

.stat-content {
  height: 168px;
  padding: 24px 16px;
  position: relative;
  z-index: 1;
}

.stat-icon {
  margin-bottom: 12px;
  color: var(--card-color, #409eff);
  opacity: 0.8;
}

.stat-value {
  font-size: 2.5em;
  font-weight: bold;
  margin-bottom: 8px;
  font-family: 'Courier New', monospace;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-trend {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  font-size: 12px;
  color: #67c23a;
  font-weight: 500;
}

.charts-row {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.chart-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #2c3e50;
  margin-top: 5px;
  margin-left: 9px;
}

.card-icon {
  color: #409eff;
}

.news-section {
  margin-top: 32px;
}

.news-card {
  border-radius: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.news-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.news-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  color: #2c3e50;
}

.news-icon {
  color: #e6a23c;
}

.news-item {
  margin-bottom: 0;
  border-radius: 12px;
  transition: all 0.2s ease;
}

.news-item:hover {
  background: #f8f9fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home {
    padding: 16px;
  }

  .header h1 {
    font-size: 20px;
  }

  .stat-value {
    font-size: 2em;
  }

  .stats-cards .el-col {
    margin-bottom: 16px;
  }

  .charts-row .el-col {
    margin-bottom: 20px;
  }
}

/* 加载动画 */
.el-card {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 图表容器样式 */
:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
  margin: -20px -20px 20px -20px;
  border-radius: 16px 16px 0 0;
}

</style>